﻿using ChuanYe.Core.Utils;
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace ChuanYe.Core.Utils
{
    public class MQClient
    {
        public MqttClient client = null;

        public string ip = string.Empty;

        public string prot = string.Empty;

        public string clientID = string.Empty;

        public string userName = string.Empty;

        public string password = string.Empty;



        public delegate void CustmerEventHandler(object sender, MqttMsgPublishEventArgs e);


        public void TryConnect()
        {
            try
            {
                client = new MqttClient(ip);
                client.Connect(clientID, userName, password);
            }
            catch(Exception ex)
            {
                client = null;
            }
        }


        public MQClient(string clientID=null)
        {
            this.ip = AppSetting.GetConfig("MQTTClient:IP");
            this.prot = AppSetting.GetConfig("MQTTClient:Port");
            this.userName = AppSetting.GetConfig("MQTTClient:UserName");
            this.password = AppSetting.GetConfig("MQTTClient:Password");
            this.clientID = (clientID ?? "ChuanYe") +"_"+ System.Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="topic">发布的主题</param>
        /// <param name="Data">发布的消息内容</param>
        public void Publish(string topic, string data,bool retain)
        {
            if (MQTTSingleKeepAlive())
            {
                client.Publish(topic, Encoding.UTF8.GetBytes(data), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, retain);
            }
        }

        /// <summary>
        /// 订阅
        /// </summary>
        /// <param name="topic">订阅的主题</param>
        public void Subscribe(string[] topic)
        {
            client.Subscribe(topic, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }


        /// <summary>
        /// MQTT保活程序
        /// </summary>
        /// <returns></returns>
        private bool  MQTTSingleKeepAlive()
        {
            try
            {
                if (client == null || client.IsConnected == false)
                {
                    TryConnect();
                    if (client != null && client.IsConnected == true)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }


    }   
}
